<template>
  <div class="role-edit-container">
    <el-card class="edit-card">
      <h2 class="form-title">编辑角色</h2>
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="role-form">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-tree
            :data="permissions"
            show-checkbox
            node-key="id"
            default-expand-all
            :props="defaultProps"
            ref="permissionTree"
            class="permission-tree"
          ></el-tree>
        </el-form-item>
        <el-form-item class="form-buttons">
          <el-button type="primary" @click="submitForm('form')" icon="el-icon-check">保存</el-button>
          <el-button @click="cancel" icon="el-icon-back">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getRoleById, updateRole } from '@/api/role'
import { getResourcesList } from '@/api/resources'

export default {
  data() {
    return {
      form: {
        id: '',
        name: '',
        permissions: []
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 25, message: '长度在 1 到 25 个字符', trigger: 'blur' }
        ],
        permissions: [
          { required: true, message: '请选择权限', trigger: 'change' }
        ]
      },
      permissions: [],
      defaultProps: {
        children: 'children',
        label: 'text'
      }
    }
  },
  created() {
    this.fetchPermissions()
    this.fetchRole()
  },
  methods: {
    async fetchRole() {
      try {
        const response = await getRoleById(this.$route.params.id)
        const roleData = response.data.data
        this.form = {
          id: roleData.id,
          name: roleData.name,
          permissions: roleData.roleResourcesList
        }
        this.$nextTick(() => {
          var s = new Array()
          for (var i = 0; i < this.form.permissions.length; i++) {
            s.push(this.form.permissions[i].resourcesId)
          }
          console.log(s)
          this.$refs.permissionTree.setCheckedKeys(s)
          this.reverseCheckKeys(s)
        })
      } catch (error) {
        console.error('获取角色信息失败:', error)
        this.$message.error('获取角色信息失败')
      }
    },
    async fetchPermissions() {
      try {
        const response = await getResourcesList()
        this.permissions = response.data.data
      } catch (error) {
        console.error('获取权限列表失败:', error)
        this.$message.error('获取权限列表失败')
      }
    },
    reverseCheckKeys(checkedKeys) {
      const allKeys = this.getAllKeys(this.permissions)
      const uncheckedKeys = allKeys.filter(key => !checkedKeys.includes(key))
      this.$refs.permissionTree.setCheckedKeys(uncheckedKeys)
      this.$refs.permissionTree.setCheckedKeys(checkedKeys, true)
    },
    getAllKeys(data) {
      let keys = []
      data.forEach(item => {
        keys.push(item.id)
        if (item.children && item.children.length > 0) {
          keys = keys.concat(this.getAllKeys(item.children))
        }
      })
      return keys
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const checkedNodes = this.$refs.permissionTree.getCheckedKeys()
          this.form.resourcesId = checkedNodes
          try {
            await updateRole(this.form)
            this.$message.success('更新角色成功')
            this.$router.push('/roles')
          } catch (error) {
            console.error('更新角色失败:', error)
            this.$message.error('更新角色失败')
          }
        }
      })
    },
    cancel() {
      this.$router.push('/roles')
    }
  }
}
</script>

<style scoped>
.role-edit-container {
  padding: 20px;
}

.edit-card {
  margin-bottom: 20px;
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409EFF;
  font-size: 24px;
  font-weight: 600;
}

.role-form {
  display: flex;
  flex-direction: column;
  max-width: 600px;
  margin: 0 auto;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
}

.form-buttons {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.form-buttons .el-button {
  margin: 0 10px;
  padding: 12px 24px;
  font-size: 14px;
}
</style>